<template>
  <div>
    <a-row>
      <a-col :span="6" class="flex">
        <Input class="flex-1" v-model:value="selectLabel" disabled />
        <a-button type="link" @click="handleShow">选择</a-button>
        <BasicModal
          title="选择"
          width="60%"
          height="500"
          @register="register"
          @cancel="open = false"
          @ok="handleOk"
        >
          <BasicTable @register="registerTable" />
        </BasicModal>
      </a-col>
    </a-row>
  </div>
</template>
<script setup lang="ts">
import { nextTick, ref } from 'vue';
import BasicTable from '@/components/Table/src/BasicTable.vue';
import { useTable } from '@/components/Table/src/hooks/useTable.ts';
import { Input } from 'ant-design-vue';
import BasicModal from '@/components/Modal/src/BasicModal.vue';
import { useModal } from '@/components/Modal/src/hooks/useModal.ts';
import { basicProps } from '@/components/Table/src/props.ts';
import { useMessage } from '@/hooks/web/useMessage';

const props = defineProps({
  value: [Array, Object, String, Number],
  label: [Array, String],
  mode: String,
  ...basicProps,
  valueField: {
    type: String,
    default: 'id',
  },
  labelField: String,
});

const emit = defineEmits(['update:value', 'change']);
const { createMessage } = useMessage();
const open = ref(false);
// 初始化赋值父组件中服务端返回的名称
const selectLabel = ref(props.label);

const [register, { openModal, closeModal }] = useModal();

const [registerTable, { getSelectRows, clearSelectedRowKeys }] = useTable({
  ...props,
  rowKey: props.valueField,
  scroll: { y: 300 },
  rowSelection: {
    // 单选是radio
    type: 'radio',
  },
  // isCanResizeParent: true,
  useSearchForm: true,
});

const handleShow = () => {
  openModal(true, {});
  nextTick(() => {
    clearSelectedRowKeys();
  })
};

const handleOk = () => {
  const rows = getSelectRows();
  if (rows && rows.length) {
    const value = rows[0][props.valueField];
    selectLabel.value = rows[0][props.labelField];
    emit('update:value', value);
    // 触发change 携带选中值和选中值对应的数据
    emit('change', value, rows[0]);
    closeModal();
  } else {
    createMessage.error('请选择一条记录！');
  }
};
</script>
<style lang="less" scoped></style>
